//
//  HeaderView.m
//  FairyDream
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 dreams. All rights reserved.
//

#import "HeaderView.h"
#import "HeaderModel.h"
#import "UIImageView+WebCache.h"
#define Width 375
#define Height 200
@interface HeaderView () <UIScrollViewDelegate>
@property (nonatomic, retain) UIScrollView *scroll;
@property (nonatomic, retain) UIImageView *imageV;
@property (nonatomic, retain) UIPageControl *page;
@property (nonatomic, strong) NSTimer *timer;

@end



@implementation HeaderView

- (void)dealloc
{
    [_scroll release];
    [super dealloc];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.numArr = [NSMutableArray array];
        
    }
    
    return self;
}

- (void)createScroll
{
    self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, Width, Height)];
    _scroll.contentSize = CGSizeMake(Width * self.numArr.count, Height);
    _scroll.contentOffset = CGPointMake(0, 0);
    [self addSubview:_scroll];
    _scroll.delegate = self;
    _scroll.pagingEnabled = YES;
    [_scroll release];
    
    for (int i = 0; i < self.numArr.count; i++) {
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(i * Width , 0, Width, Height)];
        [imageV setTag:i + 1];
        [self.scroll addSubview:imageV];
    }
    
    self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(172.5, 170, 30, 10)];
    _page.numberOfPages = self.numArr.count;
    
    [self addSubview:_page];
    

    
    [self startTimer];
}


- (void)setModelWithHeaderView:(NSArray *)array
{
    for (int i = 1; i < array.count + 1; i++) {
      UIImageView *image = (UIImageView *)[self viewWithTag:i];
    [image sd_setImageWithURL:[NSURL URLWithString:[array objectAtIndex:i - 1]]];
    }
}



- (void)nextImage
{
    NSInteger pageNum = _page.currentPage;
    
        if (pageNum == _numArr.count - 1) {
            pageNum = 0;
        }
        else
        {
            pageNum++;
        }
        CGFloat x = pageNum * Width;
        self.scroll.contentOffset = CGPointMake(x, 0);
    
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
 {
     
     //    计算页码
     //    页码 = (contentoffset.x + scrollView一半宽度)/scrollView宽度
         CGFloat scrollviewW =  _scroll.frame.size.width;
         CGFloat x = _scroll.contentOffset.x;
         int page = (x + scrollviewW / 2) /  scrollviewW;
         self.page.currentPage = page;
     }
- (void)startTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
}


@end
